<?php
class Model_Admin_Assort extends Model{

    public function getInfo($caption,$offset,$pageSize){

         $sql="select count(1)total
             from assort t
             where t.isdeleted<>'1'
             and t.caption like '%$caption%'";

        $total=DB::query(Database::SELECT,$sql)->execute()->get("total");

        $sql="select t.assortid id,t.pid,p.caption pname,t.caption,t.url,t.isdisabled,t.createdon,t.createdby
             from assort t
             left join assort p on p.assortid=t.pid
             where t.isdeleted<>'1'
             and t.caption like '%$caption%'
             order by t.createdon desc limit $offset,$pageSize";


        $data=DB::query(Database::SELECT,$sql)->execute()->as_array();

        return array("total"=>$total,"rows"=>$data);

    }
    public  function saveInfo($id,$pid,$caption,$url,$isdisabled){

        if($id==""){
            return $this->add($pid,$caption,$url,$isdisabled);
        }
        else{
            return $this->alter($id,$pid,$caption,$url,$isdisabled);
        }

    }
    private function add($pid,$caption,$url,$isdisabled){
        try {

            list($insert_id, $total_rows)= DB::insert('assort')

            ->columns(array('pid','caption','url','isdisabled','CreatedBy','CreatedOn'))
                
            ->values(array($pid,$caption,$url,$isdisabled,Session::instance()

            ->get('admin_username',NULL),date("Y-m-d h:i:sa")))->execute();

            Database::instance()->commit();

            return json_encode(array("info"=>"success","count"=>$total_rows,"id"=>$insert_id));
        }
        catch (Exception $e) {

            Database::instance()->rollback();

            return json_encode(array("info"=>"服务器错误，保存失败，请联系管理员或者重试"));
        }
    }
    private function alter($id,$pid,$caption,$url,$isdisabled){

        try {
            $total_rows=DB::update('assort')

            ->set(array('pid'=>$pid,'caption'=>$caption,'url'=>$url,'isdisabled'=>$isdisabled))

            ->where('assortid','=',$id)->execute();

            Database::instance()->commit();

            return json_encode(array("info"=>"success","count"=>$total_rows));
        }
        catch (Exception $e) {

            Database::instance()->rollback();

            return json_encode(array("info"=>"服务器错误，保存失败，请联系管理员或者重试"));
        }
    }
}